package com.example.demo.service.impl;

import com.example.demo.constant.SystemConstant;
import com.example.demo.constant.TaskConstant;
import com.example.demo.dto.CouponsListDTO;
import com.example.demo.dto.OrderListDTO;
import com.example.demo.mapper.StudentCouponsMapper;
import com.example.demo.mapper.entity.Commodity;
import com.example.demo.mapper.entity.Coupons;
import com.example.demo.mapper.entity.Order;
import com.example.demo.mapper.entity.StudentCoupons;
import com.example.demo.service.StudentCouponsService;
import com.example.demo.utils.CouponsUtil;
import com.example.demo.utils.PageBo;
import com.example.demo.utils.PageVo;
import com.example.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Lucy
 * @create 2024-02-20 13:30
 */
@Slf4j
@Service
public class StudentCouponsServiceImpl implements StudentCouponsService {

    @Autowired
    private StudentCouponsMapper couponsMapper;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public Coupons selectCouponsById(int couponsId) {
        return couponsMapper.selectCouponsById(couponsId);
    }

    @Override
    public void insertStudentCoupons(int studentId, int couponsId) {
        Coupons coupons = couponsMapper.selectCouponsById(couponsId);
        StudentCoupons studentCoupons = new StudentCoupons();
        studentCoupons.setStudentId(studentId);
        studentCoupons.setCouponsId(couponsId);
        int advertiserId = coupons.getAdvertiserId();
        String couponNumber;
        do {
            couponNumber = CouponsUtil.generateCouponNumber(advertiserId);
        } while (redisUtil.hasKey(couponNumber)); // 检查是否重复
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 日期时间格式
        String endDateStr = coupons.getEndDate();
        LocalDateTime endDate = LocalDateTime.parse(endDateStr, formatter);
        LocalDateTime now = LocalDateTime.now(); // 当前日期时间
        Duration duration = Duration.between(now, endDate);
        long seconds = duration.getSeconds();
        redisUtil.set(couponNumber, TaskConstant.COUPON_NUMBER + ":" + studentId + ":" + couponsId, seconds);// 将新编号添加到redis中
        studentCoupons.setCouponsNumber(couponNumber);
        couponsMapper.insertStudentCoupons(studentCoupons);
    }

    @Override
    public PageVo<CouponsListDTO> getStatusCouponsList(PageBo pageBo, int studentId, int status) {
        List<StudentCoupons> studentCouponsList = couponsMapper.selectStatusCouponsList(studentId, status);
        List<CouponsListDTO> couponsListDTOList = new ArrayList<>();
        for (StudentCoupons studentCoupons : studentCouponsList) {
            CouponsListDTO dto = new CouponsListDTO();
            Coupons coupons = couponsMapper.selectCouponsById(studentCoupons.getCouponsId());
            dto.setCouponsId(coupons.getCouponsId());
            dto.setCouponsNumber(studentCoupons.getCouponsNumber());
            dto.setCouponsType(coupons.getCouponsType());
            dto.setCouponsName(coupons.getCouponsName());
            dto.setCouponsLabel(CouponsUtil.generateCouponLabel(coupons));
            dto.setEndDate(coupons.getEndDate());
            dto.setStatus(status);
            couponsListDTOList.add(dto);
        }
        return new PageVo<>(pageBo, couponsListDTOList);
    }

    @Override
    public PageVo<CouponsListDTO> getNewlyAcquiredCouponsList(PageBo pageBo, int studentId, int status) {
        List<StudentCoupons> studentCouponsList = couponsMapper.selectStatusCouponsList(studentId, status);
        List<CouponsListDTO> couponsListDTOList = new ArrayList<>();
        for (StudentCoupons studentCoupons : studentCouponsList) {
            // 获取当前时间戳
            long currentTime = System.currentTimeMillis();
            // 获取优惠券获得时间戳
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date acquireDate;
            try {
                acquireDate = dateFormat.parse(studentCoupons.getAcquireDate());
            } catch (ParseException e) {
                // 记录无效日期字符串相关信息的日志
                log.error("Invalid date string: {}. Student: {}, Coupon: {}", studentCoupons.getAcquireDate(), studentId, studentCoupons.getCouponsId());
                continue; // 继续处理下一个优惠券
            }
            long acquireTime = acquireDate.getTime();
            // 判断是否是最新获得的优惠券（假设最近7天为最新）
            boolean isNewlyAcquired = currentTime - acquireTime <= 7 * 24 * 3600 * 1000;
            if(!isNewlyAcquired){
                continue;
            }
            CouponsListDTO dto = new CouponsListDTO();
            Coupons coupons = couponsMapper.selectCouponsById(studentCoupons.getCouponsId());
            dto.setCouponsId(coupons.getCouponsId());
            dto.setCouponsNumber(studentCoupons.getCouponsNumber());
            dto.setCouponsType(coupons.getCouponsType());
            dto.setCouponsName(coupons.getCouponsName());
            dto.setCouponsLabel(CouponsUtil.generateCouponLabel(coupons));
            dto.setEndDate(coupons.getEndDate());
            dto.setStatus(status);
            couponsListDTOList.add(dto);
        }
        return new PageVo<>(pageBo, couponsListDTOList);
    }

    @Override
    public PageVo<CouponsListDTO> getExpiringCouponsList(PageBo pageBo, int studentId, int status) {
        List<StudentCoupons> studentCouponsList = couponsMapper.selectStatusCouponsList(studentId, status);
        List<CouponsListDTO> couponsListDTOList = new ArrayList<>();
        for (StudentCoupons studentCoupons : studentCouponsList) {
            CouponsListDTO dto = new CouponsListDTO();
            Coupons coupons = couponsMapper.selectCouponsById(studentCoupons.getCouponsId());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 获取当前时间戳
            long currentTime = System.currentTimeMillis();
            // 获取优惠券结束时间戳
            Date endDate;
            try {
                endDate = dateFormat.parse(coupons.getEndDate());
            } catch (ParseException e) {
                // 记录无效日期字符串相关信息的日志
                log.error("Invalid date string: {}. Student: {}, Coupon: {}", coupons.getEndDate(), studentId, studentCoupons.getCouponsId());
                continue; // 继续处理下一个优惠券
            }
            long endTime = endDate.getTime();
            // 判断是否是即将过期的优惠券（假设在当前日期的7天内即将过期的优惠券）
            boolean isExpiringSoon = endTime - currentTime <= 7 * 24 * 3600 * 1000;
            if(!isExpiringSoon){
                continue;
            }
            dto.setCouponsId(coupons.getCouponsId());
            dto.setCouponsNumber(studentCoupons.getCouponsNumber());
            dto.setCouponsType(coupons.getCouponsType());
            dto.setCouponsName(coupons.getCouponsName());
            dto.setCouponsLabel(CouponsUtil.generateCouponLabel(coupons));
            dto.setEndDate(coupons.getEndDate());
            dto.setStatus(status);
            couponsListDTOList.add(dto);
        }
        return new PageVo<>(pageBo, couponsListDTOList);
    }

    @Override
    public StudentCoupons selectStudentCoupons(int studentId, int couponsId) {
        return couponsMapper.selectStudentCoupons(studentId, couponsId);
    }

    @Override
    public String selectAddressById(int advertiserId) {
        return couponsMapper.selectAddressById(advertiserId);
    }

    @Override
    public void updateStudentCouponsStatus(int studentId, int couponsId) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime lastUpdatedTime = LocalDateTime.now();
        String updatedAt = lastUpdatedTime.format(formatter);
        couponsMapper.updateStudentCouponsStatus(studentId, couponsId, updatedAt);
    }

    @Override
    public StudentCoupons selectStudentCouponsByNumber(String couponsNumber) {
        return couponsMapper.selectStudentCouponsByNumber(couponsNumber);
    }

}
